package com.agentlab.imitation.service;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.SessionFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.agentlab.imitation.bean.AssociationZy;
import com.agentlab.imitation.bean.AssociationZyRule;
import com.agentlab.imitation.service.base.DaoSupport;

@Service
@Transactional
public class AssociationZyServiceBean extends DaoSupport<AssociationZy> implements AssociationZyService {
	@Resource
	SessionFactory factory;
	static List<AssociationZyRule> ruleList;

	public void init() {
		System.out.println("AssociationZyServiceBean.init() begin");
		List<AssociationZy> list = getAll();
		ruleList = new ArrayList<AssociationZyRule>();
		for (AssociationZy az : list) {
			AssociationZyRule rule = new AssociationZyRule();
			String caption = az.getNodeCaption();
			String front = caption.substring(0, caption.indexOf("->"));
			String end = caption.substring(caption.indexOf("->") + 2, caption.length());
			// System.out.println("front:" + front);
			// System.out.println("end:" + end);
			String[] frontArr = front.split(",");
			String[] endArr = end.split(",");
			List frontList = new ArrayList<String>();
			for (String str : frontArr) {
				// System.out.println("front:" + str.substring(0,
				// str.indexOf("=")));
				frontList.add(str.substring(0,str.indexOf("=")).trim());
			}
			for (int i=0;i<endArr.length;i++) {
				endArr[i] =  endArr[i].substring(0,	endArr[i].indexOf("="));
			}
			rule.setRules(frontList);
			rule.setResult(endArr);
			rule.setProbability(az.getProbability());
			rule.setSupport(az.getSupport());
			ruleList.add(rule);
		}
		System.out.println("AssociationZyServiceBean.init() end");
	}
	/**
	 * 传入专业或专业组合，返回匹配的关联规则
	 */
	public List<AssociationZyRule> getRelatedZy(String[] zys) {
		if (ruleList == null)
			init();
		for (String zy : zys) { //循环所选专业 
			for(AssociationZyRule rule:ruleList){
				if(rule.getRules().contains(zy)){ //规则中是否包括该专业
					rule.countTime();  //专业匹配计数
				}
			}
		}
		List<AssociationZyRule> matchRules = new ArrayList<AssociationZyRule>();
		for(AssociationZyRule rule:ruleList){
			if(rule.getTime() == rule.getRuleLength()){ //规则中是否包括该专业
				matchRules.add(rule); //专业匹配计数
			}
		}
		return matchRules;
	}

	public void delete(Serializable... entityids) {
		// TODO Auto-generated method stub

	}

	@SuppressWarnings("unchecked")
	public List<AssociationZy> getAll() {
		List<AssociationZy> list = factory.getCurrentSession().createQuery(" from AssociationZy ").setCacheable(true).list();
		return list;
	}

}
